# Copyright (c) 2025 Huawei Technologies Co. Ltd.
# deepinsight is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
from starlette.requests import HTTPConnection

from deepinsight.service.auth.base import AuthProvider, AuthManager
from deepinsight.service.auth.openeuler_intelligence.session_manager import SessionManager
from deepinsight.service.auth.openeuler_intelligence.session_service import UserHTTPException


class OpenEulerIntelligenceAuthProvider(AuthProvider):
    """OpenEuler Intelligence认证提供者"""

    def _get_session_id(self, request: HTTPConnection) -> str:
        """从请求中获取session ID"""
        try:
            session_id = None
            auth_header = request.headers.get("Authorization")
            if auth_header and auth_header.startswith("Bearer "):
                session_id = auth_header.split(" ", 1)[1]
            elif "ECSESSION" in request.cookies:
                session_id = request.cookies["ECSESSION"]

            if not session_id:
                raise UserHTTPException(
                    status_code=401,
                    retcode=401,
                    rtmsg="Authentication Error: No session ID found",
                    data=""
                )

            return session_id
        except UserHTTPException:
            raise
        except Exception as e:
            raise UserHTTPException(
                status_code=401,
                retcode=401,
                rtmsg=f"Authentication Error: {str(e)}",
                data=""
            )

    async def verify_credentials(self, request: HTTPConnection) -> bool:
        """验证session是否有效"""
        session_id = self._get_session_id(request)
        return await SessionManager.verify_user(session_id)

    async def get_user_id(self, request: HTTPConnection) -> str:
        """从session中获取用户ID"""
        session_id = self._get_session_id(request)
        user_sub = await SessionManager.get_user_sub(session_id)

        if not user_sub:
            raise UserHTTPException(
                status_code=401,
                retcode=401,
                rtmsg="Authentication Error: User not found",
                data=""
            )

        return user_sub


# 注册认证提供者
AuthManager.register_provider("openeuler_intelligence", OpenEulerIntelligenceAuthProvider)
